package jfdi.event;

import android.graphics.Rect;
import android.view.MotionEvent;

import util.Mlog;

public class ClickDetector implements TouchListener {
    
    private ClickHandler mHandler;
    private boolean mActive;
    
    public interface ClickHandler {
        public Rect getBounds();
        public void onSelect(int x, int y);
        public void onDeselect(int x, int y);
        public void onClick(int x, int y);
    }
    
    public ClickDetector(ClickHandler ch) {
        mHandler = ch;
        mActive = false;
    }
    
    public boolean isActive() {
        return mActive;
    }
    
    public void onTouchEvent(MotionEvent evt) {
        int x = (int) evt.getX();
        int y = (int) evt.getY();
        Rect b = mHandler.getBounds();
        if (MotionEvent.ACTION_DOWN == evt.getActionMasked()) {
            if (b.contains(x, y)) {
                mActive = true;
                mHandler.onSelect(x, y);
            }
        } else if (MotionEvent.ACTION_UP == evt.getActionMasked()) {
            if (b.contains(x, y)) {
                mActive = false;
                mHandler.onClick(x, y);
                mHandler.onDeselect(x, y);
            }
        } else if (MotionEvent.ACTION_MOVE == evt.getActionMasked()) {
            if (b.contains(x, y)) {
                mHandler.onSelect(x, y);
            } else {
                mHandler.onDeselect(x, y);
            }
        } else if (MotionEvent.ACTION_CANCEL == evt.getActionMasked()) {
            mActive = false;
            mHandler.onDeselect(x, y);
        }
    }

}
